package com.yzx.lifeassistants.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.BikingRouteOverlay;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.navisdk.adapter.BaiduNaviManager.NaviInitListener;
import com.baidu.navisdk.adapter.BaiduNaviManager.RoutePlanListener;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.MyPoupWindowAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.utils.DensityUtils;
import com.yzx.lifeassistants.utils.FileUtils;
import com.yzx.lifeassistants.utils.LogcatUtils;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 美食导航
 * @author: yzx
 * @time: 2016-4-12 上午9:55:31
 */
@SuppressLint({ "InflateParams", "HandlerLeak" })
public class FoodRouteActivity extends BaseActivity implements OnClickListener,
		OnGetRoutePlanResultListener {

	private ImageButton backBtn;// 返回按钮
	private TextView typeTV;// 规划类型
	private ImageButton guideBtn;// 语音导航
	private MapView mMapView;// 百度底图

	private BaiduMap mBaiduMap;// 百度地图
	private LocationClient mLocationClient;// 定位
	private BDLocationListener mListener;// 定位监听
	private RoutePlanSearch mSearch;// 路线搜索

	private CircularLoadingDialog dialog;// 加载框
	private LatLng destLL;// 目的地坐标
	private Boolean isFirstLoc;// 是否第一次定位
	private LatLng mLatLng;// 定位结果
	private PopupWindow popupWindow;// 类型选择框
	private int type = 0;// 类型

	public static List<Activity> activityList;//
	private static final String APP_FOLDER_NAME = "找我";// 文件名
	private Handler ttsHandler;// 内部TTS播报状态回传handler
	private String mSDCardPath;// SD卡路径
	private String authinfo;// 验证信息
	private Boolean guideInitSuccess;// 导航初始化是否成功

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_food_route);
		init();
		initView();
		setListener();
		initPoupWindow();
		initData();
		initMap();
	}

	/**
	 * 
	 * @Description: 初始化
	 */
	private void init() {
		Intent intent = getIntent();
		if (null == intent) {

		} else {
			destLL = intent.getParcelableExtra("foodLocation");
		}
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		backBtn = (ImageButton) findViewById(R.id.food_route_back_btn);
		typeTV = (TextView) findViewById(R.id.food_route_type_tv);
		guideBtn = (ImageButton) findViewById(R.id.food_route_guide_btn);
		mMapView = (MapView) findViewById(R.id.food_route_mapview);
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		typeTV.setOnClickListener(this);
		guideBtn.setOnClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化PoupWindow弹框
	 */
	@SuppressWarnings("deprecation")
	private void initPoupWindow() {
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = layoutInflater.inflate(R.layout.poupwindow, null);
		ListView groupLV = (ListView) view.findViewById(R.id.poupwindow_lv);
		// 加载数据
		List<String> groupList = new ArrayList<String>();
		groupList.add("步行线路");
		groupList.add("骑行线路");
		groupList.add("驾车线路");
		MyPoupWindowAdapter groupAdapter = new MyPoupWindowAdapter(this,
				groupList);
		groupLV.setAdapter(groupAdapter);
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// 创建一个PopuWidow对象
		popupWindow = new PopupWindow(view, windowManager.getDefaultDisplay()
				.getWidth() / 2,
				windowManager.getDefaultDisplay().getHeight() / 3);
		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		groupLV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long arg3) {
				type = position;
				if (0 == position) {
					typeTV.setText("步行线路");
				} else if (1 == position) {
					typeTV.setText("骑行线路");
				} else if (2 == position) {
					typeTV.setText("驾车线路");
				}
				if (popupWindow != null) {
					popupWindow.dismiss();
				}
				searchRoute();
			}
		});
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		activityList = new LinkedList<Activity>();
		activityList.add(this);
		guideInitSuccess = false;
		isFirstLoc = true;
		dialog = new CircularLoadingDialog(this);
		type = 0;
		typeTV.setText("步行线路");
		ttsHandler = new Handler() {
			public void handleMessage(Message msg) {
				int type = msg.what;
				switch (type) {
				case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
					showToastMsg("导航开始");
					break;
				}
				case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
					showToastMsg("导航结束");
					break;
				}
				default:
					break;
				}
			}
		};
	}

	/**
	 * 
	 * @Description: 初始化地图
	 */
	private void initMap() {
		mMapView.showScaleControl(false);
		mMapView.showZoomControls(false);
		mBaiduMap = mMapView.getMap();
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
				MyLocationConfiguration.LocationMode.FOLLOWING, true, null));
		// 定位初始化
		mLocationClient = new LocationClient(this);
		mListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mListener);
		LocationClientOption option = new LocationClientOption();
		// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setLocationMode(LocationMode.Hight_Accuracy);
		// 设置坐标类型
		option.setCoorType("bd09ll");
		// 可选，默认false,设置是否使用gps
		option.setOpenGps(true);
		// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setScanSpan(30000);
		// 可选，设置是否需要地址信息，默认不需要
		option.setIsNeedAddress(true);
		// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setLocationNotify(true);
		// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationDescribe(true);
		// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIsNeedLocationPoiList(true);
		// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
		option.setIgnoreKillProcess(false);
		// 可选，默认false，设置是否收集CRASH信息，默认收集
		option.SetIgnoreCacheException(false);
		// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		option.setEnableSimulateGps(false);
		option.setNeedDeviceDirect(true);
		mLocationClient.setLocOption(option);
		mSearch = RoutePlanSearch.newInstance();
		mSearch.setOnGetRoutePlanResultListener(this);
		BNOuterLogUtil.setLogSwitcher(true);
		startLocation();// 开始定位
		if (initDirs()) {
			initNavi();// 初始化导航
		}
	}

	/**
	 * 
	 * @Description: 开始定位
	 */
	private void startLocation() {
		mLocationClient.start();// 开始定位
	}

	/**
	 * 
	 * @ClassName: 定位监听
	 */
	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null) {
				showToast("定位失败，请确认是否设置了定位权限~", false);
				return;
			}
			mLatLng = new LatLng(location.getLatitude(),
					location.getLongitude());
			if (isFirstLoc) {
				isFirstLoc = false;
				MyLocationData locData = new MyLocationData.Builder()
						.accuracy(location.getRadius())
						// 此处设置开发者获取到的方向信息，顺时针0-360
						.direction(100).latitude(location.getLatitude())
						.longitude(location.getLongitude()).build();
				mBaiduMap.setMyLocationData(locData);
				MapStatus.Builder builder = new MapStatus.Builder();
				builder.target(mLatLng).zoom(18.0f);
				mBaiduMap.animateMapStatus(MapStatusUpdateFactory
						.newMapStatus(builder.build()));
				searchRoute();// 开始规划
			}
		}

	}

	/**
	 * 
	 * @Description: 搜索规划路线
	 */
	private void searchRoute() {
		if (null == mLatLng || null == destLL) {
			showToast("", false);
			return;
		}
		PlanNode st = PlanNode.withLocation(mLatLng);
		PlanNode en = PlanNode.withLocation(destLL);
		dialog.show();
		if (0 == type) {
			mSearch.walkingSearch(new WalkingRoutePlanOption().from(st).to(en));
		} else if (1 == type) {
			mSearch.bikingSearch(new BikingRoutePlanOption().from(st).to(en));
		} else if (2 == type) {
			mSearch.drivingSearch(new DrivingRoutePlanOption().from(st).to(en));
		}

	}

	/**
	 * 
	 * @Description: 初始化文件路径
	 */
	private boolean initDirs() {
		mSDCardPath = FileUtils.getSDCardPath();
		if (mSDCardPath == null) {
			return false;
		}
		LogcatUtils.e(mSDCardPath);
		File f = new File(mSDCardPath, APP_FOLDER_NAME);
		if (!f.exists()) {
			try {
				f.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * 
	 * @Description: 初始化导航
	 */
	private void initNavi() {
		BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME,
				new NaviInitListener() {
					@Override
					public void onAuthResult(int status, String msg) {// 验证
						if (0 == status) {
							authinfo = "key校验成功!";
						} else {
							authinfo = "key校验失败, " + msg;
						}
						LogcatUtils.i(authinfo);
					}

					public void initSuccess() {// 成功
						LogcatUtils.i("百度导航引擎初始化成功");
						guideInitSuccess = true;
						initSetting();
					}

					public void initStart() {// 开始
						LogcatUtils.i("百度导航引擎初始化开始");
					}

					public void initFailed() {// 失败
						guideInitSuccess = false;
						LogcatUtils.e("百度导航引擎初始化失败");
					}

				}, null, ttsHandler, null);

	}

	/**
	 * 
	 * @Description: 导航设置
	 */
	private void initSetting() {
		BNaviSettingManager
				.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
		BNaviSettingManager
				.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
		BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
		BNaviSettingManager
				.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
		BNaviSettingManager
				.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.food_route_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.food_route_type_tv: {// 规划类型
			popupWindow.showAsDropDown(v,
					-typeTV.getWidth() / 2 + DensityUtils.dp2px(this, 20), 0);
			break;
		}
		case R.id.food_route_guide_btn: {// 语音导航
			if (guideInitSuccess) {
				BNRoutePlanNode sNode = new BNRoutePlanNode(mLatLng.longitude,
						mLatLng.latitude, "", null, CoordinateType.BD09LL);
				BNRoutePlanNode eNode = new BNRoutePlanNode(destLL.longitude,
						destLL.latitude, "", null, CoordinateType.BD09LL);
				if (sNode != null && eNode != null) {
					List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
					list.add(sNode);
					list.add(eNode);
					BaiduNaviManager.getInstance().launchNavigator(this, list,
							1, true, new FoodRoutePlanListener(sNode));
				} else {
					showToast("导航失败~", false);
				}
			} else {
				showToast("导航失败~", false);
			}

			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: 导航监听
	 */
	public class FoodRoutePlanListener implements RoutePlanListener {

		private BNRoutePlanNode mBNRoutePlanNode = null;

		public FoodRoutePlanListener(BNRoutePlanNode node) {
			mBNRoutePlanNode = node;
		}

		@Override
		public void onJumpToNavigator() {
			/*
			 * 设置途径点以及resetEndNode会回调该接口
			 */
			for (Activity ac : activityList) {
				if (ac.getClass().getName().endsWith("FoodGuideActivity")) {
					return;
				}
			}
			Intent intent = new Intent(FoodRouteActivity.this,
					FoodGuideActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("ROUTE_PLAN_NODE",
					(BNRoutePlanNode) mBNRoutePlanNode);
			intent.putExtras(bundle);
			startActivity(intent);// 开始导航

		}

		@Override
		public void onRoutePlanFailed() {
			showToast("算路失败~", false);
		}
	}

	/**
	 * 
	 * @Description: 在主线程显示消息
	 */
	public void showToastMsg(final String msg) {
		FoodRouteActivity.this.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				showToast(msg, true);
			}
		});
	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.food_route_top_ll);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.food_route_top_ll);
		}

	}

	@Override
	public void onGetBikingRouteResult(BikingRouteResult result) {
		dialog.dismiss();
		mBaiduMap.clear();
		dialog.dismiss();
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			showToast("抱歉，未找到结果~", false);
		}

		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {

			return;
		}

		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			BikingRouteOverlay overlay = new BikingRouteOverlay(mBaiduMap);
			overlay.setData(result.getRouteLines().get(0));
			overlay.addToMap();
			overlay.zoomToSpan();
		}
	}

	@Override
	public void onGetDrivingRouteResult(DrivingRouteResult result) {
		dialog.dismiss();
		mBaiduMap.clear();
		dialog.dismiss();
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			showToast("抱歉，未找到结果~", false);
		}

		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {

			return;
		}

		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaiduMap);
			overlay.setData(result.getRouteLines().get(0));
			overlay.addToMap();
			overlay.zoomToSpan();
		}
	}

	@Override
	public void onGetTransitRouteResult(TransitRouteResult result) {

	}

	@Override
	public void onGetWalkingRouteResult(WalkingRouteResult result) {
		mBaiduMap.clear();
		dialog.dismiss();
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			showToast("抱歉，未找到结果~", false);
		}

		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {

			return;
		}

		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			WalkingRouteOverlay overlay = new WalkingRouteOverlay(mBaiduMap);
			overlay.setData(result.getRouteLines().get(0));
			overlay.addToMap();
			overlay.zoomToSpan();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mLocationClient.stop();
		mMapView.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 退出时销毁定位
		mLocationClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
	}
}
